/**
 * Created by lixiaodi on 2019/05/09 0027.
 */

mini.parse();
//得到页面上的表单
var form = new mini.Form("form1");

var tableN = mini.getByName('tableClassName');
var tableChClassName = mini.getByName('tableChClassName');
var creatPerson = mini.getByName('creatPerson');		//创建人id（新增保存时）
var creatPName = mini.getByName('creatPName');			//创建人姓名（编辑显示时）
var classId = '';			//分类id
var modelId = '';			//模型id
var nowAction = '';			//当前状态：新增/编辑
var tableEl = $('#tableEl');
//通过缓存获取用户信息
var item2 = localStorage.getItem("item");
var userInfoObj = JSON.parse(item2);
var userId;		//建模人的用户id，如果是新增，id是登陆人id，如果是编辑，那么id是查询到的id

var creatPersonVal = '';
//父页面给子页面传值
function SetData(data) {
	//跨页面传递的数据对象，克隆后才可以安全使用
    data = mini.clone(data);
    var modelData = data.classData;
    if (data.action == "edit") {
    	nowAction = "edit";
    	creatPerson.hide();
    	tableEl.hide();
    	//查询单条信息
    	var modelId = data.modelId;
    	var modelIdObj = {
    		   id: modelId
    	};
    	var modelIdStr = JSON.stringify(modelIdObj);
    	console.log(modelIdStr);
    	//加密
    	//modelIdStr = encrypt(modelIdStr);
    	console.log(modelIdStr);
    	//根据模型id查询该模型信息并赋值
    	$.ajax({
    		url: ajaxUrl + "/model/findById.do",
    		//url: "http://192.168.31.65:8080/bpm/model/findById.do",
    		type:"post",
    		data: modelIdStr,
    		contentType : "application/utf-8",
    		success: function (data) {
    			//解密
    			// var decryptData = decrypt(data);
	 			if(data.state == 'success'){
	 				var modelInfo = data.data;
	 				console.log(modelInfo);
					//得到分类id
	 		    	classId = modelInfo.modelClass.id;
	 		    	//转化时间格式
					modelInfo.createDate = formatDate(modelInfo.createDate);
					//赋值
					form.setData(modelInfo);
					creatPName.setValue(modelInfo.createPName);
					creatPersonVal = modelInfo.creatPerson;
					//creatPerson.setValue();
	 			}else{
	 				console.log('数据为空');
	 			}
	 		    //grid.setData(data.treeDate);
    		},
    		error:function(data){
    			mini.alert('请求失败');
    		}
    	});
    }else if(data.action == "new"){
    	nowAction = "new";
    	creatPName.hide();
    	//得到分类id
    	classId = modelData.id;
    	//创建人赋值
    	creatPerson.setValue(userInfoObj.uName);
    	userId = userInfoObj.userId;
    }
}
//保存
function SaveData(){
	//校验
    form.validate();
    if (form.isValid() == false){
    	return
	}
    	// return;
    if(creatPersonVal){
    	userId = creatPersonVal
    }
    var db = mini.get("btnEdit1");
    var dbInfoId = db.getValue();
    //得到数据
	var ids = form.getData();
	console.log(ids);
	var modelInfo = {
			id: ids.id,
			code : ids.code,
			modelName: ids.modelName,
			creatPerson : userId,
			creatDate: ids.createDate,
            modelClass : classId,
			// model: modellist.id + '',
			className: ids.tableClassName,
			classChName: ids.tableChClassName,
			pid: "0",
			dbInfoId : dbInfoId
	};
	console.log(modelInfo);
    var modelString = JSON.stringify(modelInfo);
    console.log(modelString);
	debugger
    $.ajax({
    	//url: "http://192.168.31.65:8080/bpm/model/insertModel.do",
        url: ajaxUrl + "/model/insertModel.do",
        type: 'POST',
        data: modelString,
        contentType : "application/json",
        success: function (data) {
        	debugger
        	console.log(data);
        	var decryptData = data;
        	//判断赋值
        	if(decryptData.state == 'success'){
        		if(nowAction == 'new'){
	        		var modellist = decryptData.data; 
	        		var tableInfo = {
	        				model: modellist.id + '',
							className: ids.tableClassName,
							classChName: ids.tableChClassName,
							pid: "0",
							dbInfoId : dbInfoId
	        		}
	        		var tableInfoStr = JSON.stringify(tableInfo);
        			//创建主表
            		$.ajax({
            			url: ajaxUrl + "/Base/BaseClassAndTable.do",
            			//url: "http://192.168.31.65:8080/bpm/Base/BaseClassAndTable.do",
            	        type: "post",
            	        contentType : "application/utf-8",
            	        data: tableInfoStr,
            	        success: function(data){
            	        	//mini,alert(data.data);
            	        	CloseWindow("save");
							debugger
            	        },
            	        error: function (data){
            	        	alert('请求失败');
            	        }
            		})
        		}else{
        			console.log('不可编辑主表');
        			CloseWindow("save");
        		}
        		
			 }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('请求失败');
            CloseWindow();
        }
    });   
}
//模型编码校验重复
function findByModelCode(){
	var ids = form.getData();
	var modelCode = ids.code;
	//请求
	$.ajax({
		url  	: ajaxUrl + '/model/findByCode.do',
		type 	: 'POST',
		data 	: {
			code : modelCode
		},
		success : function(data){
			console.log(data);
			if(data.state == 'error'){
				mini.alert(data.message);
				//mini.getByName('code').setValue(''); 
			}
		},
		error   : function(message) {
			mini.alert(message);
		}
	})
}
//模型名称校验是否重复
function findByModelName(){
	var ids = form.getData();
	var modelName = ids.modelName;
	//请求
	$.ajax({
		url  	: ajaxUrl + '/model/findByModelName.do',
		type 	: 'POST',
		data 	: {
			modelName: modelName
		},
		success : function(data){
			if(data.state == 'error'){
				mini.alert(data.message);
				//mini.getByName('modelName').setValue(''); 
			}
		},
		error   : function(message) {
			mini.alert(message);
		}
	})
}
//当鼠标失去焦点的时候校验表名
function findByTableClassName(e){
    //得到输入的英文表名
    var tableNValue = tableN.getValue();
    if(tableNValue){
        var regs = /^[\w\_]*$/;     //只能是数字和字母和下划线
        var reg = /^[0-9]*$/;       //纯数字
        if(regs.test(tableNValue)){
            if(!reg.test(tableNValue)){
                //如果不是数字也不是空，校验与数据库表名是否重复
                $.ajax({
                    url : ajaxUrl + "/tableClass/findAll.do",
                    type : "POST",
                    success : function(data){
                        var allTables = data.data;
                        for(var i = 0; i < allTables.length; i++){
                            if(tableNValue == allTables[i].tableClassName){
                            	//信号量改变
                                tnChange = false;
                                mini.alert("表名重复，请重新填写");
                                return false;
                            }
                        }
                    }
                });
            }else{
            	//信号量改变
                tnChange = false;
                mini.alert("表名不能为纯数字");
                return false;
            }
        }else{
        	//信号量改变
            tnChange = false;
            mini.alert("表名只能为字母，数字和下划线");
            return false;
        }
    }else{
    	//信号量改变
        tnChange = false;
        mini.alert("表名不能为空");
        return false;
    }
}
//校验模块必输
function onNotSpaceValidation(e) {
    if (e.isValid) {
        if (!e.value) {
            e.errorText = "不能为空";
            e.isValid = false;
        }
    }
}
//关闭子页面
function CloseWindow(action) {
    if (action == "close" && form.isChanged()) {
        if (confirm("数据被修改了，是否先保存？")) {
            return false;
        }
    }
    if (window.CloseOwnerWindow) return window.CloseOwnerWindow(action);
    else window.close();
}
function onOk(e) {
    SaveData();
	CloseWindow("ok");
}
function onCancel(e) {
    CloseWindow("cancel");
}


function onButtonEdit(){
	mini.open({
		url : "../pages/creatModelManage/dbSource.html",
		title: "选择列表",
		width: 650,
		height: 380,
		onload: function () {
			var iframe = this.getIFrameEl();
			// var data = { action: "edit", id: row.modularId };
			// iframe.contentWindow.SetData(data);
		},
		ondestroy: function (action) {
			if (action == "ok") {
				var iframe = this.getIFrameEl();
				var data = iframe.contentWindow.GetData();
				data = mini.clone(data);    //必须
				if (data) {
					var btnEdit = mini.get("btnEdit1");
					btnEdit.setValue(data.id);
					btnEdit.setText(data.cDBName);
					btnEdit.doValueChanged();
				}
			}
		}
	});

}